<template>
  <div id="app" :style="background">
    <NavBar></NavBar>
    <div class="container-fluid">
      <div class="row">
        <!--<SideBar></SideBar>-->
        <ContentBoard></ContentBoard>
      </div>
    </div>
    <NewRoom @commit="join"></NewRoom>
    <FriendBar></FriendBar>
  </div>
</template>
<script>
import ContentBoard from './components/ContentBoard'
import FriendBar from './components/FriendBar'
import NavBar from './components/NavBar'
import NewRoom from './components/NewRoom'
import { mapActions, mapGetters, mapMutations } from 'vuex'
/* eslint-disable */
export default {
    name: 'app',
    components: {
        ContentBoard,FriendBar,NavBar,NewRoom
    },
    data () {
        return {
        }
    },
    computed: {
        ...mapGetters(['backMM','token']),
        background () {
            var mmid = this.backMM;
            return mmid > 0 ? 'background:url("/rcn/mm/'+mmid+'.jpg") center top;background-size:cover;' : ''
        }
    },
    methods: {
        ...mapMutations({
            connSocket:'SOCKET_CONNECTION_STR',
            setRoomStates:'ROOM_STATES',
            setRTCConfig:'RTC_CONFIG',
        }),
        ...mapActions({
            joinRoom: 'JOIN_ROOM',
            socketOn: 'SOCKET_LISTENER',
            answer: 'ANSWER_2_FRIEND',
            receive: 'ANSWER_FROM_FRIEND',
            ice: 'ICE_FROM_FRIEND',
            offer: 'OFFER_2_FRIEND',
            sendOffer2All: 'OFFER_2_ALL',
            doCamera:'CONTROL_LOCAL_CAMERA',
        }),
        join ({roomName,userName}){
            var vm = this;
            vm.joinRoom({roomName,userName})
            .then((res)=>{
                console.log(res);
                vm.socketOn({ 
                    'OFFER' : msg => vm.answer({ name:msg.from, dsp:msg.dsp }) ,
                    'ANSWER': msg => vm.receive({ name:msg.from, dsp:msg.dsp }) ,
                    'ICE': msg => vm.ice({ name:msg.from,type:msg.type, ice:msg.ice }),
                    'JOIN_ROOM': friend => {
                        this.$store.commit('FRIEND_JOINED',friend);
                        vm.offer(friend);
                    },
                    'LEAVE_ROOM': friend => this.$store.commit('FRIEND_LEFT',friend),
                });
                vm.doCamera().then((ret)=>{
                    if(ret) vm.sendOffer2All();
                });
            })
            .catch((err)=>{
                alert(err.info);
            })
        }
    },
    created () {
        //习惯性缓存this,防止调用时忘记上下文
        var vm = this;
        //连接websocket服务器
        vm.connSocket('/');
        //获取背景图
        vm.$http.get('/rcn/mm').then(function(res){
            vm.setRoomStates({ backMM: res.body.id });
        });
        //获取ICE配置
        vm.$http.get('/ice/a').then((res)=>{
            console.log('ice config:',JSON.stringify(res.body.iceServers));
            vm.setRTCConfig({iceServers : JSON.parse(JSON.stringify(res.body.iceServers))});
        });
    }
}
</script>